//
//  BQOAuthViewModel.swift
//  BQWB
//
//  Created by laibingqiang on 16/10/25.
//  Copyright © 2016年 laibingqiang. All rights reserved.
//

import UIKit

class BQOAuthViewModel: NSObject {
    
    static let shared:BQOAuthViewModel = {
        
        let m = BQOAuthViewModel()
        
        return m
        
        }()
    //解决沙盒频繁调用
    var accountModel:BQOAuthModel?
    
    var isLogin:Bool{
        
        if accountModel?.access_token == nil{
            
            return false
        }
        
        return true
    }
    
    var access_token:String?{
        
        if accountModel?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending{
            
            return accountModel?.access_token
        }
        else
        {
            return nil
        }
    }
    
    override init() {
        super.init()
        
        accountModel = getUserAccountModel()
    }
    
    let file:String = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")
    
    func saveUserAccountModel(model:BQOAuthModel){
        //防止accountModel为nil
        accountModel = model
        
        NSKeyedArchiver.archiveRootObject(model, toFile: file)
    }
    
    func getUserAccountModel()->BQOAuthModel?{
        
        let result =  NSKeyedUnarchiver.unarchiveObject(withFile: file)
        
        return result as? BQOAuthModel
    }

}

//OAuth授权相关
extension BQOAuthViewModel{
    
    func getUserAccount(code:String,finish:@escaping (Bool)->()){
        
        NetworkTool.shared.getUserAccount(code: code, success: { (response) in
            
            guard let res = response else{
                finish(false)
                return
            }
            
            let model:BQOAuthModel = BQOAuthModel.yy_model(withJSON: res)
            
            self.getUserInfo(model: model, finish: finish)
            }) { (error) in
                
                finish(false)
        }
     }
    
    func getUserInfo(model:BQOAuthModel,finish:@escaping (Bool)->()){
        
        NetworkTool.shared.getUserInfo(model: model, success: { (response) in
            
            guard let res = response as? [String:Any] else{
                finish(false)
                return
            }
            
            model.screen_name = res["screen_name"] as? String
            
            model.avatar_large = res["avatar_large"] as? String
            
            BQOAuthViewModel.shared.saveUserAccountModel(model: model)

            finish(true)
            }) { (error) in
                
                finish(false)
        }
    }
}
